//
//  QDNetWorkingAPI.m
//  ylh-app-primary-ios
//
//  Created by YueWen on 2018/11/29.
//  Copyright © 2018 巨商汇. All rights reserved.
//

#import "QDNetWorkingAPI.h"
#import "NWNetWorkingManager.h"

@interface QDNetWorkingAPI ()

@end

@implementation QDNetWorkingAPI

@synthesize delegate = _delegate;

- (void)resumeNetworking
{
    //进行回调
    if (self.hasDelegate && NetWorkingAPIHasSel(self,@selector(networkingAPIWillRequest:))) {
        [self.delegate networkingAPIWillRequest:self];
    }
    
    [NWNetWorkingManager requestWithUrlString:self.url Method:self.method Parameters:self.parameters success:^(NSURLSessionDataTask *dataTask, NSDictionary *data) {
        
        [self setValue:dataTask forKey:@"sessionTask"];
        
        //结束
        if (self.hasDelegate && NetWorkingAPIHasSel(self,@selector(networkingAPIEndRequest:))) {
            [self.delegate networkingAPIEndRequest:self];
        }
        
        
        if (![[data valueForKey:@"respcod"] isEqualToString:@"01"]) {//表示出问题
            
            if (self.hasDelegate && NetWorkingAPIHasSel(self, @selector(networkingAPI:fail:info:))) {
                [self.delegate networkingAPI:self fail:[NSError errorWithDomain:QDSafeString([data valueForKey:@"respmsg"]) code:[[data valueForKey:@"respcod"] integerValue] userInfo:nil] info:data];
            }
            
            else if (self.hasDelegate && NetWorkingAPIHasSel(self, @selector(networkingAPI:fail:))) {
                [self.delegate networkingAPI:self fail:[NSError errorWithDomain:QDSafeString([data valueForKey:@"respmsg"]) code:[[data valueForKey:@"respcod"] integerValue] userInfo:nil]];
            }
            
        } else {// 数据完成
            
            if (self.hasDelegate && NetWorkingAPIHasSel(self,@selector(networkingAPI:completeWithData:))) {
                [self.delegate networkingAPI:self completeWithData:data];
            }
        }
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [self setValue:dataTask forKey:@"sessionTask"];
        
        if (self.hasDelegate && NetWorkingAPIHasSel(self,@selector(networkingAPIEndRequest:))) {//结束
            [self.delegate networkingAPIEndRequest:self];
        }
        if (self.hasDelegate && NetWorkingAPIHasSel(self,@selector(networkingAPI:fail:))) {
            [self.delegate networkingAPI:self fail:error];
        }
    }];
}

@end
